#!/usr/bin/env node

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = 3000;

// 中间件配置
app.use(cors());
app.use(bodyParser.json());

// 批量重命名文件API
app.post('/api/rename-files', (req, res) => {
  try {
    const { directory, pattern, replacement, recursive = false } = req.body;
    
    if (!directory || !pattern || replacement === undefined) {
      return res.status(400).json({ success: false, message: '缺少必要的参数' });
    }
    
    const result = renameFiles(directory, pattern, replacement, recursive);
    res.json({ success: true, message: '文件重命名完成', data: result });
  } catch (error) {
    console.error('重命名文件时出错:', error);
    res.status(500).json({ success: false, message: error.message });
  }
});

// 内容查找替换API
app.post('/api/replace-content', (req, res) => {
  try {
    const { directory, search, replace, extensions = [], recursive = false } = req.body;
    
    if (!directory || !search) {
      return res.status(400).json({ success: false, message: '缺少必要的参数' });
    }
    
    // 处理扩展名格式
    const extensionArray = Array.isArray(extensions) ? extensions : 
      typeof extensions === 'string' && extensions.trim() ? extensions.split(',').map(ext => ext.trim()) : [];
    
    const result = replaceInFiles(directory, search, replace, extensionArray, recursive);
    res.json({ success: true, message: '文件内容替换完成', data: result });
  } catch (error) {
    console.error('替换文件内容时出错:', error);
    res.status(500).json({ success: false, message: error.message });
  }
});

// 目录统计API
app.post('/api/directory-stats', (req, res) => {
  try {
    const { directory, recursive = false } = req.body;
    
    if (!directory) {
      return res.status(400).json({ success: false, message: '缺少必要的参数' });
    }
    
    const stats = getDirectoryStats(directory, recursive);
    res.json({
      success: true, 
      message: '目录统计完成', 
      data: {
        fileCount: stats.fileCount,
        directoryCount: stats.directoryCount || 0,
        totalSize: stats.totalSize,
        averageFileSize: stats.averageSize,
        fileTypes: Object.entries(stats.extensions || {}).map(([ext, count]) => ({
          extension: ext === '无扩展名' ? '' : ext,
          count: count,
          totalSize: stats.extensionSizes?.[ext] || 0
        }))
      }
    });
  } catch (error) {
    console.error('获取目录统计信息时出错:', error);
    res.status(500).json({ success: false, message: error.message });
  }
});

// 批量重命名文件函数
function renameFiles(directory, pattern, replacement, recursive) {
  const renamedFiles = [];
  const files = fs.readdirSync(directory);
  
  files.forEach(file => {
    const filePath = path.join(directory, file);
    const stat = fs.statSync(filePath);
    
    if (stat.isDirectory()) {
      if (recursive) {
        const subDirResults = renameFiles(filePath, pattern, replacement, true);
        renamedFiles.push(...subDirResults);
      }
    } else {
      const newName = file.replace(new RegExp(pattern, 'g'), replacement);
      if (newName !== file) {
        const newPath = path.join(directory, newName);
        fs.renameSync(filePath, newPath);
        renamedFiles.push({
          oldName: file,
          newName: newName,
          path: directory
        });
      }
    }
  });
  
  return renamedFiles;
}

// 在文件中查找并替换内容函数
function replaceInFiles(directory, search, replace, extensions, recursive) {
  const updatedFiles = [];
  const files = fs.readdirSync(directory);
  
  files.forEach(file => {
    const filePath = path.join(directory, file);
    const stat = fs.statSync(filePath);
    
    if (stat.isDirectory()) {
      if (recursive) {
        const subDirResults = replaceInFiles(filePath, search, replace, extensions, true);
        updatedFiles.push(...subDirResults);
      }
    } else {
      const ext = path.extname(file).toLowerCase();
      if (extensions.length === 0 || extensions.includes(ext)) {
        let content = fs.readFileSync(filePath, 'utf8');
        const newContent = content.replace(new RegExp(search, 'g'), replace);
        
        if (newContent !== content) {
          fs.writeFileSync(filePath, newContent, 'utf8');
          updatedFiles.push({
            fileName: file,
            path: directory,
            changeCount: (content.match(new RegExp(search, 'g')) || []).length
          });
        }
      }
    }
  });
  
  return updatedFiles;
}

// 获取目录统计信息函数
function getDirectoryStats(directory, recursive) {
  let stats = {
    fileCount: 0,
    directoryCount: 0,
    totalSize: 0,
    extensions: {},
    extensionSizes: {}
  };
  
  function traverse(dir) {
    try {
      const files = fs.readdirSync(dir);
      
      files.forEach(file => {
        try {
          const filePath = path.join(dir, file);
          const stat = fs.statSync(filePath);
          
          if (stat.isDirectory()) {
            stats.directoryCount++;
            if (recursive) {
              traverse(filePath);
            }
          } else {
            stats.fileCount++;
            stats.totalSize += stat.size;
            
            const ext = path.extname(file).toLowerCase() || '无扩展名';
            stats.extensions[ext] = (stats.extensions[ext] || 0) + 1;
            stats.extensionSizes[ext] = (stats.extensionSizes[ext] || 0) + stat.size;
          }
        } catch (error) {
          console.warn(`处理文件 ${file} 时出错: ${error.message}`);
        }
      });
    } catch (error) {
      console.warn(`访问目录 ${dir} 时出错: ${error.message}`);
    }
  }
  
  traverse(directory);
  stats.averageSize = stats.fileCount > 0 ? stats.totalSize / stats.fileCount : 0;
  
  return stats;
}

// 启动服务器
app.listen(PORT, () => {
  console.log(`文件处理API服务器已启动，端口: ${PORT}`);
  console.log('可用API:');
  console.log('- POST /api/rename-files - 批量重命名文件');
  console.log('- POST /api/replace-content - 替换文件内容');
  console.log('- POST /api/directory-stats - 获取目录统计信息');
});